<template>
  <div class="content">
    <div class="map">
      <div id="preview-map" class="preview-map-container">地图加载中...</div>
      <!-- <div v-if="!loadingDashboardInfo" class="statisticalPanel">
        <div class="statistical">
          <p class="statisticalTitle">今日耗能</p>
          <div class="statisticalInfo">
            <img src="@/assets/images/dashboardicon1.png" />
            <div class="statisticalInfoView statisticalInfoView1">
              <div class="leftz">
                <p>30天耗能(KWh)</p>
                <p>30天充电次数</p>
                <p>30天充电时长(小时)</p>
              </div>
              <div class="rightz">
                <p :title="data.electricitySum">{{ data.electricitySum }}</p>
                <p :title="data.chargeSum">{{ data.chargeSum }}</p>
                <p :title="data.durationSum">{{ data.durationSum }}</p>
              </div>
            </div>
          </div>
        </div>
        <div class="statistical">
          <p class="statisticalTitle">设备统计</p>
          <div class="statisticalInfo">
            <img src="@/assets/images/dashboardicon2.png" />
            <div class="statisticalInfoView statisticalInfoView2">
              <div class="leftz">
                <p>电站数</p>
                <p>端口数</p>
                <p>空闲端口数</p>
                <p>充电中端口数</p>
                <p>失联端口数</p>
                <p>故障端口数</p>
              </div>
              <div class="rightz">
                <p :title="data.stationNum">{{ data.stationNum }}</p>
                <p :title="data.deviceNum">{{ data.deviceNum }}</p>
                <p :title="data.idleNum">{{ data.idleNum }}</p>
                <p :title="data.chargingNum">{{ data.chargingNum }}</p>
                <p :title="data.offlineNum">{{ data.offlineNum }}</p>
                <p :title="data.faultNum">{{ data.faultNum }}</p>
              </div>
            </div>
          </div>
        </div>
        <div class="statistical" v-if="userStatisticsVisible">
          <p class="statisticalTitle">用户统计</p>
          <div class="statisticalInfo">
            <img src="@/assets/images/dashboardicon3.png" />
            <div class="statisticalInfoView statisticalInfoView3">
              <div class="leftz">
                <p>活跃用户</p>
                <p>30天消费金额（元）</p>
              </div>
              <div class="rightz">
                <p :title="data.activeUser">{{ data.activeUser }}</p>
                <p :title="data.consumptionSum">{{ data.consumptionSum }}</p>
              </div>
            </div>
          </div>
        </div>
      </div> -->
    </div>
    <div class="dashboard-address-container">
      <HycAddressCascader
        :insertResetZoom="true"
        show-label
        v-model="area"
        :level="1"
      />
    </div>
    <el-dialog
      class="dashboard-dialog"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <img src="@/assets/images/insurance-advertisement.png" alt="" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="noShowSevenDays">7天内不再展示</el-button>
        <el-button type="primary" @click="openPDF">查看详情</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import _ from 'lodash'
import { debounce } from '@/utils'
import { areaStationData, queryDataByUserInfo } from '@/api/dashboard'
// import { loadMap, reverseGeoCode } from '@/utils/map-loaderV3'
// import { reverseGeoCode } from '@/utils/map-loaderV3'
import AMapLoader from '@amap/amap-jsapi-loader'
import HycAddressCascader from '@/components/hycAddressCascader'
// import mapSettings from './config/mapSetting2'
// import getCustomOverlay from '@/utils/CustomOverlay'
const whiteList = ['ADMIN', 'SELF_OPERATION_ADMIN']
const zoomRange = ['country', 'province', 'city', 'district']
const zoomLevel = {
  country: {
    min: 5,
    max: 6,
  },
  province: {
    min: 6,
    max: 9,
  },
  city: {
    min: 9,
    max: 11,
  },
  district: {
    min: 11,
    max: 13,
  },
}
export default {
  name: 'Statistics',
  components: { HycAddressCascader },
  computed: {
    roleType() {
      return this.$store.getters.roleType
    },
    userStatisticsVisible() {
      return whiteList.includes(this.roleType)
    },
  },
  data() {
    return {
      area: {},
      loadingDashboardInfo: true,
      fullscreen: false,
      map: null,
      zoom: 'country',
      zoomId: null,
      mapQueryParams: {
        zoom: 'country',
        zoomId: null,
      },
      overlayData: [],
      overlayList: [],
      maskoverlay: null,
      isControl: false,
      isClick: false,
      isAreaSelect: false,
      // centerPoint: '全国',
      initCenterPoint: [116.397085, 39.908703],
      areaName: '全国',
      aMapZoomChangeLister: null,
      dialogVisible: false,
    }
  },
  watch: {
    overlayList(val) {
      val.forEach((item) => this.map.add(item))
    },
    deep: true,
    area(val) {
      let lastArea = ''
      let code = ''
      let lastLevel = ''
      ;['province', 'city'].forEach((key) => {
        let areaData = val[key] ? val[key].split(',') : []
        if (areaData && areaData.length > 0) {
          lastArea = lastArea + areaData[1]
          code = areaData[2] || ''
          lastLevel = key
        }
      })
      if (lastArea !== '') {
        this.isAreaSelect = true
        if (lastArea === '全国') {
          this.map.setZoomAndCenter(5, this.initCenterPoint)
          this.mapQueryParams = {
            zoom: 'country',
            zoomId: null,
          }
          this._getMapData()
          return
        }

        if (val.city || val.province) {
          var PlaceSearchOptions = {
            city: '全国',
            pageSize: 10,
            pageIndex: 1,
            extensions: 'base',
          }
          var MapSearch = new window.AMap.PlaceSearch(PlaceSearchOptions)
          window.AMap.event.addListener(MapSearch, 'complete', (results) => {
            let point = results.poiList.pois[0].location
            this.map.setZoomAndCenter(zoomLevel[lastLevel].min + 1, point)
          })

          MapSearch.search(lastArea)
          this.mapQueryParams = {
            zoom: lastLevel,
            zoomId: code,
          }
          this._getMapData()
          return
        }
      }
    },
  },
  methods: {
    //  用户首次登录显示dialog，且弹窗提示一天只会出现一次
    initDialog() {
      if (document.cookie.length > 0) {
        console.log('oneDay-cookies: ' + document.cookie)
        let arr = document.cookie.split('; ') //通过; 将数据转成数组
        for (let i = 0; i < arr.length; i++) {
          let index = arr[i].indexOf('=') //返回第一个“=”所在的位置
          if (arr[i].substring(0, index) === 'oneDay') {
            //  cookie存在,将isExist设置为true
            this.isExist = true
            break
          }
          if (arr[i].substring(0, index) === 'sevenDay') {
            //  点击”7天内不再展示“，则未来7天内用户登录后不展示弹窗
            return
          }
        }
      }
      // cookie不存在
      if (!this.isExist) {
        // this.dialogVisible = true
        this.dialogVisible = false
        // 过期时间设置为次日凌晨
        let expiresTime = new Date()
        expiresTime.setTime(new Date().getTime() + 24 * 60 * 60 * 1000)
        expiresTime.setHours(0)
        expiresTime.setMinutes(0)
        expiresTime.setSeconds(0)
        window.document.cookie =
          'oneDay' + '=' + new Date() + ';path=/;expires=' + expiresTime
      }
    },
    //  弹窗提示七天内不再展示
    noShowSevenDays() {
      if (document.cookie.length > 0) {
        console.log('sevenDay-cookies: ' + document.cookie)
        let arr = document.cookie.split('; ') //通过; 将数据转成数组
        for (let i = 0; i < arr.length; i++) {
          let index = arr[i].indexOf('=') //返回第一个“=”所在的位置
          if (arr[i].substring(0, index) === 'sevenDay') {
            //cookie存在,将isSeven设置为true
            this.isSeven = true
            break
          }
        }
      }
      // cookie不存在
      if (!this.isSeven) {
        this.dialogVisible = false
        // 过期时间设置为7天后次日凌晨
        let expiresTime = new Date()
        expiresTime.setTime(new Date().getTime() + 7 * 24 * 60 * 60 * 1000)
        expiresTime.setHours(0)
        expiresTime.setMinutes(0)
        expiresTime.setSeconds(0)
        window.document.cookie =
          'sevenDay' + '=' + new Date() + ';path=/;expires=' + expiresTime
      }

      if (document.cookie) {
        document.cookie = 'oneDay' + '=;expires=Thu, 01 Jan 1970 00:00:00 UTC'
        this.dialogVisible = false
        console.log('clearCookies: ' + document.cookie)
      }
    },
    openDetails() {
      window.open(`${process.env.VUE_APP_SERVER_URL}/insurance/index.html#/`)
    },
    openPDF() {
      window.open(`${process.env.VUE_APP_SERVER_URL}/IntroductionOfVehicle.pdf`)
    },
    _registMapEvents() {
      if (!this.map) return
      window.onresize = () => {
        this.map.setCenter(this.initCenterPoint)
      }

      // this.map.onload = () => {
      //   this.isControl = false
      // }

      // this.map.ontilesloaded = () => {
      //   this.isControl = true
      // }

      // this.map.on('complete', () => {
      //   this.isControl = true
      // })
      window.AMap.event.addListener(this.map, 'complete', () => {
        this.isControl = true
      })

      // this.map.onzoomend = debounce(async () => {
      //   if (!this.isControl) return
      //   if (this.isClick) {
      //     this.isClick = false
      //     return
      //   }

      //   if (this.isAreaSelect) {
      //     this.isAreaSelect = false
      //     return
      //   }
      //   this.mapQueryParams = await this._getMapParams()
      //   this.mapQueryParams.zoom === 'country'
      //     ? this._initParams({
      //         zoomId: null,
      //         zoom: 'country',
      //         areaName: '全国',
      //       })
      //     : this._getMapData()
      // })
      // let startZoom
      // let endZoom
      // this.map.on('zoomstart', () => {
      //   if (!this.isControl) return
      //   startZoom = this.map.getZoom()
      // })

      // this.map.on('zoomend', () => {
      //   if (!this.isControl) return
      //   if (this.isClick) {
      //     this.isClick = false
      //     return
      //   }
      //   endZoom = this.map.getZoom()
      // })
      // if (startZoom < endZoom) return //只考虑缩回的问题,放大不做处理

      this.aMapZoomChangeLister = window.AMap.event.addListener(
        this.map,
        'zoomchange',
        debounce(async () => {
          if (!this.isControl) return
          if (this.isClick) {
            this.isClick = false
            return
          }

          if (this.isAreaSelect) {
            this.isAreaSelect = false
            return
          }
          this.mapQueryParams = await this._getMapParams()
          this.mapQueryParams.zoom === 'country'
            ? this._initParams({
                zoomId: null,
                zoom: 'country',
                areaName: '全国',
              })
            : this._getMapData()
        })
      )
    },
    _getMapData() {
      areaStationData(this.mapQueryParams).then((res) => {
        if (_.isEqual(this.overlayData, res)) return
        this.overlayData = res
        this._createOverlay2()
      })
    },
    _createOverlay2() {
      if (!this.map) return
      this.overlayList.forEach((item) => this.map.remove(item))
      this.overlayList = []
      this.overlayData.forEach((item) => {
        let index = zoomRange.findIndex(
          (item) => item === this.mapQueryParams.zoom
        )
        let indexNext = index === zoomRange.length - 1 ? index : index + 1
        let zoomNext = zoomRange[indexNext]
        let address = zoomRange
          .slice(1, indexNext + 1)
          .map((key) => item[key])
          .join('')
        if (index === zoomRange.length - 1) {
          var text = new window.AMap.Text({
            text: `${item.stationName}，端口数:${item.plugNum}`,
            position: new window.AMap.LngLat(item.stationLng, item.stationLat),
            style: {
              position: 'absolute',
              padding: '6px 10px',
              'border-radius': '10px',
              'background-color': '#649c00',
              color: '#fff',
              'font-size': '12px',
              'text-align': 'center',
              'background-clip': 'padding-box',
              'z-index': '1000',
            },
          })
          this.overlayList.push(text)
        } else {
          var PlaceSearchOptions = {
            city: '全国',
            pageSize: 10,
            pageIndex: 1,
            extensions: 'base',
          }

          var MapSearch = new window.AMap.PlaceSearch(PlaceSearchOptions) //构造PlaceSearch类
          window.AMap.event.addListener(MapSearch, 'complete', (results) => {
            let point = results.poiList.pois[0].location
            var markerContent = `<div class="pointOverlay2" title="（电站数：${item.stationNum}, 插口数：${item.plugNum})"><div class="pointOverlayTop"></div><div>电站：${item.stationNum}</div><div>插口：${item.plugNum}</div></div>`
            var marker = new window.AMap.Marker({
              position: new window.AMap.LngLat(point.lng, point.lat),
              content: markerContent,
              offset: new window.AMap.Pixel(-40, -40),
            })
            marker.on('click', () => {
              this.isClick = true
              this.map.setZoomAndCenter(zoomLevel[zoomNext].min + 1, point)
              this.mapQueryParams = {
                zoom: zoomNext,
                zoomId: item.areaCode,
              }
              this._initParams({
                zoom: zoomNext,
                zoomId: item.areaId,
                areaName: address,
              })
            })
            marker.on('mouseover', () => {
              marker.setzIndex(99999)
            })
            marker.on('mouseout', () => {
              marker.setzIndex(1)
            })
            this.overlayList.push(marker)
          })
          window.AMap.event.addListener(MapSearch, 'error', (results) => {
            console.log(results)
          })

          MapSearch.search(address) //关键字查询
        }
      })
    },
    // _createOverlay() {
    //   if (!this.map) return
    //   this.overlayList.forEach((item) => this.map.removeOverlay(item))
    //   let CustomOverlay = getCustomOverlay()
    //   this.overlayList = []
    //   this.overlayData.forEach((item) => {
    //     let index = zoomRange.findIndex(
    //       (item) => item === this.mapQueryParams.zoom
    //     )
    //     let indexNext = index === zoomRange.length - 1 ? index : index + 1
    //     let zoomNext = zoomRange[indexNext]
    //     let address = zoomRange
    //       .slice(1, indexNext + 1)
    //       .map((key) => item[key])
    //       .join('')
    //     if (index === zoomRange.length - 1) {
    //       let label = new window.BMapGL.Label(
    //         item.stationName + '，端口数:' + item.plugNum,
    //         {
    //           position: new window.BMapGL.Point(
    //             item.stationLng,
    //             item.stationLat
    //           ),
    //         }
    //       )
    //       let style = {
    //         color: '#fff',
    //         fontSize: '12px',
    //         padding: '5px',
    //         backgroundColor: '#649C00',
    //         border: '0',
    //         borderRadius: '10px',
    //       }
    //       let hoverStyle = {
    //         backgroundColor: 'orange',
    //         zIndex: 99999,
    //       }
    //       let normalStyle = {
    //         backgroundColor: '#649C00',
    //         zIndex: 1,
    //       }
    //       label.setStyle(style)
    //       label.addEventListener('mouseout', () => {
    //         label.setStyle(normalStyle)
    //       })
    //       label.addEventListener('mouseover', () => {
    //         label.setStyle(hoverStyle)
    //       })
    //       this.overlayList.push(label)
    //     } else {
    //       let LocalSearch = new window.BMapGL.LocalSearch(address, {
    //         onSearchComplete: (results) => {
    //           let point = results.getPoi(0).point
    //           if (point) {
    //             let clickCallback = () => {
    //               this.isClick = true
    //               this.map.centerAndZoom(point, zoomLevel[zoomNext].min + 1)
    //               this.mapQueryParams = {
    //                 zoom: zoomNext,
    //                 zoomId: item.areaCode,
    //               }
    //               this._initParams({
    //                 zoomId: item.areaId,
    //                 zoom: zoomNext,
    //                 areaName: address,
    //               })
    //             }
    //             let mySquare = new CustomOverlay(
    //               point,
    //               item[zoomNext],
    //               item,
    //               clickCallback,
    //               'pointOverlay2',
    //               '#00A6F3',
    //               '#00A6F3'
    //             )
    //             this.overlayList.push(mySquare)
    //           }
    //         },
    //       })

    //       LocalSearch.search(address)
    //     }
    //   })
    // },
    initMap() {
      // 百度
      // loadMap().then(() => {
      //   let mapOptions = {
      //     minZoom: 6,
      //     maxZoom: 19,
      //     enableMapClick: false,
      //   }
      //   this.map = new window.BMapGL.Map('preview-map', mapOptions)
      //   this.map.setMapStyleV2({
      //     styleJson: mapSettings,
      //   })
      //   this.map.centerAndZoom('全国') //为了将广东省份显示在地图可视区，修改成如下 this.map.centerAndZoom('中国')
      //   this.map.enableScrollWheelZoom(true)
      //   this.map.disableDoubleClickZoom()
      //   this.map.enableAutoResize()
      //   this._registMapEvents()
      //   this._getMapData()
      //   this.initData()
      // })

      AMapLoader.load({
        key: process.env.VUE_APP_AMAP_AK, // 申请好的Web端开发者Key，首次调用 load 时必填
        // version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ['AMap.PlaceSearch', 'AMap.Geocoder'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
        .then((AMap) => {
          this.map = new AMap.Map('preview-map', {
            zoom: 5, //初始化地图级别
            center: this.initCenterPoint, //初始化地图中心点位置
            zooms: [5, 20],
            doubleClickZoom: false,
            scrollWheel: true,
            mapStyle: process.env.VUE_APP_AMAP_STYLE,
          })
          this._registMapEvents()
          this.area = {
            province: '2498,四川省,undefined',
          }
          // this._getMapData()
          this.initData()
        })
        .catch((e) => {
          console.log(e)
        })
    },
    initData() {
      queryDataByUserInfo().then((res) => {
        this.loadingDashboardInfo = false
        this.data = res
        this.data.durationSum = parseInt((res.durationSum / 60) * 100) / 100
      })
    },
    _initParams({ zoomId, zoom, areaName }) {
      this.zoomId = zoomId
      this.zoom = zoom
      this.areaName = areaName
      this._getMapData()
    },
    _getZoomLevel() {
      if (!this.map) return
      let zoom
      let zoomNum = this.map.getZoom()
      zoom =
        (zoomNum <= zoomLevel.country.max && 'country') ||
        (zoomNum <= zoomLevel.province.max && 'province') ||
        (zoomNum <= zoomLevel.city.max && 'city') ||
        (zoomNum > zoomLevel.district.min && 'district')
      return zoom
    },
    _getMapParams() {
      return new Promise((resolve) => {
        let zoom = this._getZoomLevel()
        let point = this.map.getCenter()
        // reverseGeoCode(point).then(
        //   (res) => {
        //     let params = {
        //       zoom: zoom,
        //       zoomId: zoom === 'country' ? null : res.addressComponent.adcode,
        //     }
        //     resolve(params)
        //   },
        //   (error) => {
        //     reject(error)
        //   }
        // )
        var geocoder = new window.AMap.Geocoder({})
        var lnglat = [point.lng, point.lat]

        geocoder.getAddress(lnglat, (status, res) => {
          if (status === 'complete' && res.info === 'OK') {
            console.log(res)
            let params = {
              zoom: zoom,
              zoomId:
                zoom === 'country'
                  ? null
                  : res.regeocode.addressComponent.adcode,
            }
            resolve(params)
          }
        })
      })
    },
  },
  activated() {
    if (this.map) {
      this._registMapEvents()
    }
  },
  deactivated() {
    window.onresize = null
    if (this.map) {
      // this.map.onload = null
      // this.map.onzoomend = null
      if (this.aMapZoomChangeLister) {
        window.AMap.event.removeListener(this.aMapZoomChangeLister)
      }
    }
  },
  deystroyed() {
    window.onresize = null
    if (this.map) {
      // this.map.onload = null
      // this.map.onzoomend = null
      if (this.aMapZoomChangeLister) {
        window.AMap.event.removeListener(this.aMapZoomChangeLister)
      }
    }
  },
  mounted() {
    this.initMap()
    this.initDialog()
  },
}
</script>
<style lang="scss" scoped>
.content {
  height: 100%;
  width: 100%;
  position: relative;
  display: flex;
  justify-content: space-between;
  .map {
    width: 100%;
    height: 100%;

    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    .preview-map-container {
      width: calc(100% - 10px);
      height: calc(100% - 10px);
      margin: auto;
      background: #0c0d0f !important;
    }
  }
}

.statisticalPanel {
  width: 430px;
  max-height: 94%;
  position: absolute;
  top: 20px;
  right: 20px;
  padding-right: 30px;
  overflow-y: auto;
  .statistical {
    width: 100%;
    height: 210px;
    background: rgba(13, 15, 20, 0.6);
    padding: 20px;
    border: 2px solid rgba(118, 199, 239, 0.6);
    border-radius: 6px;
    &:nth-child(2),
    &:nth-child(3) {
      margin-top: 30px;
    }
    .statisticalTitle {
      color: #fff;
      font-size: 14px;
    }
    .statisticalInfo {
      margin-top: 10px;
      overflow: hidden;
      img {
        width: 90px;
        float: left;
        margin-top: 20px;
      }
      .statisticalInfoView {
        width: 210px;
        float: left;
        margin-left: 36px;
        .leftz {
          float: left;
          text-align: left;
          color: #76c7ef;
          font-size: 12px;
          width: 120px;

          p {
            margin: 0;
          }
        }
        .rightz {
          font-size: 12px;
          color: #fff;
          float: right;
          text-align: right;
          width: 80px;
          margin-right: 10px;
          p {
            width: 100%;
            white-space: nowrap;
            text-overflow: ellipsis;
            overflow: hidden;
            margin: 0;
          }
        }
      }
      .statisticalInfoView1 {
        margin-top: 34px;
      }
      .statisticalInfoView2 {
        margin-top: 10px;
      }
      .statisticalInfoView3 {
        margin-top: 40px;
      }
    }
  }
}

.dashboard-address-container {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 999;
  background: #fff;
}

.dashboard-dialog {
  ::v-deep .el-dialog {
    border-radius: 4px 4px 0px 0px;
    .el-dialog__header {
      background: #fff;
      .el-dialog__title {
        color: #fff;
      }
      .el-dialog__close {
        font-weight: 700;
        color: #0c0d0f;
      }
    }
    .el-dialog__footer {
      .dialog-footer {
        .el-button {
          width: 150px;
        }
      }
    }
  }
  img {
    width: 100%;
    height: 100%;
  }
}
</style>
